import axios from 'axios';
import { message } from 'ant-design-vue';
import { v4 as uuidv4 } from 'uuid';
// import { resetCurrentUserInfo } from '@/utils/userInfo';

const instance = axios.create({
  baseURL: '/',
});

instance.interceptors.request.use((data: any) => {
  try {
    const method = data.method.toUpperCase();
    if (method === 'POST') {
      const d = data.data;
      if (d) {
        d.gid = uuidv4();
      } else {
        data.data = {
          gid: uuidv4(),
        };
      }
    } else if (method === 'GET') {
      if (data.params) {
        data.params.gid = uuidv4();
      } else {
        data.params = {
          gid: uuidv4(),
        };
      }
    }
  } catch (e) {
    console.log(e);
  }
  return data;
});

instance.interceptors.response.use(async (data: any) => {
  const responseData = data.data;
  const { notifySucess, hideErrMsg } = data.config || {};
  if (data.request.responseURL.indexOf('/oaLogin') === -1) {
    if (responseData.code === -3) {
      console.log('-3');
      // 未登录或者登录过期，页面清除用户信息并跳转到登录页面
      // resetCurrentUserInfo();
      if (window.location.pathname !== '/') {
        window.location.href = '/';
      }
    }
  }

  if (responseData.code === 0) {
    if (notifySucess === true) {
      message.success(responseData.message || '操作成功');
    } else if (typeof notifySucess === 'string') {
      message.success(responseData.message || '操作成功');
    }
  } else if (hideErrMsg !== true) {
    console.log('responseData.message', responseData.message);
    message.error(responseData.message || '请求失败');
  }

  return responseData;
}, (err: any) => {
  if (!axios.isCancel(err) || !(err.config.data || {}).hideErrMsg) { message.error(err.message || '请求异常'); }
  return Promise.resolve(err);
});

export const { get, post } = instance;

export default instance;
